<template>
  <div class="box-full flex-col box-border overflow-hidden m-relative">
    <div class="m-absolute b-0 w-full t-0 box-border">
      <a-scrollbar style="height: 100%; overflow-y: auto; overflow-x: hidden">
        <a-card :bordered="false" class="mt-10 round-8">
          <div class="flex flex-a-c h-20 mb-14">
            <div class="h-full bg-theme round-2 w-4 mr-10"></div>
            <span class="font-size-30 text333">用户看板</span>
            <template v-if="props.allChannel && props.allChannel.length">
              <a-select
                popup-container=".select-box"
                placeholder="选择渠道方筛选"
                v-model="staticParams.channelIds"
                multiple
                allow-clear
                :allow-search="false"
                class="ml-10 mr-20 flex-1"
                :max-tag-count="1"
                @change="channelIdsChange"
              >
                <a-option v-for="item in props.allChannel" :value="item.channelId" :key="item.channelId">{{
                  item.name
                }}</a-option>
              </a-select>
            </template>
          </div>
          <div
            v-if="dateTime"
            class="h-32 flex-center round-4 px-10"
            style="border: 1px solid var(--color-border-3)"
            @click="openCalendar"
          >
            {{ dateTime[0].format('YY/MM/DD') }} 至 {{ dateTime[1].format('YY/MM/DD') }}
          </div>
          <van-calendar
            :default-date="dateDefault"
            v-model:show="dataShow"
            type="range"
            switch-mode="year-month"
            :show-confirm="false"
            @confirm="onConfirmDate"
          />
          <div class="round-8 h-10n bgfff w-full flex flex-a-c">
            <div class="flex flex-a-c mt-10">
              <div class="box-border flex round-4 h-6n border-3 w-fit cursor-pointer mr-10 font-size-22">
                <div
                  class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                  :class="tabIndex === 1 ? 'bgtheme textfff' : 'border-theme text-theme'"
                  @click="changeData(1)"
                >
                  今日实时
                </div>
                <div
                  class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                  :class="tabIndex === 2 ? 'bgtheme textfff' : 'border-theme text-theme'"
                  @click="changeData(2)"
                >
                  近7天
                </div>
                <div
                  class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                  :class="tabIndex === 3 ? 'bgtheme textfff' : 'border-theme text-theme'"
                  @click="changeData(3)"
                >
                  近15天
                </div>
                <div
                  class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                  :class="tabIndex === 4 ? 'bgtheme textfff' : 'border-theme text-theme'"
                  @click="changeData(4)"
                >
                  近30天
                </div>
                <div
                  class="flex-1 h-full flex-center nowrap px-8 box-border round-4 mr-10"
                  :class="tabIndex === 5 ? 'bgtheme textfff' : 'border-theme text-theme'"
                  @click="changeData(5)"
                >
                  本月
                </div>
                <div
                  class="flex-1 h-full flex-center nowrap px-8 box-border round-4"
                  :class="tabIndex === 6 ? 'bgtheme textfff' : 'border-theme text-theme'"
                  @click="changeData(6)"
                >
                  上月
                </div>
              </div>
            </div>
          </div>
          <a-spin class="w-full" :loading="staticLoading">
            <div class="w-full pb-4">
              <a-checkbox-group class="mt-10 w-full flex flex-wrap" v-model="checkKey">
                <template v-for="item in totalDataO" :key="item.key">
                  <a-checkbox :value="item.value" style="width: fit-content">
                    <template #checkbox="{ checked }">
                      <a-space
                        align="start"
                        class="custom-checkbox-card"
                        :class="{ 'custom-checkbox-card-checked': checked }"
                      >
                        <div className="custom-checkbox-card-mask">
                          <div className="custom-checkbox-card-mask-dot" />
                        </div>
                        <div class="mt--4">
                          <a-typography-text type="secondary" class="font-size-20 text23">
                            {{ item.label }}<span v-if="item.unit">（{{ item.unit }}）</span>
                          </a-typography-text>
                          <div className="custom-checkbox-card-title">
                            <a-statistic
                              show-group-separator
                              :value="Number(totalDatas[item.key])"
                              :precision="item.precision"
                              :value-from="0"
                              :value-style="{ fontWeight: 'bold' }"
                              animation
                            >
                            </a-statistic>
                          </div>
                        </div>
                      </a-space>
                    </template>
                  </a-checkbox>
                </template>
              </a-checkbox-group>
            </div>
          </a-spin>
          <a-spin class="w-full" :loading="staticLoading">
            <Chart ref="ChartRef" :checkKey="checkKey" :dataFormat="dataFormat" />
          </a-spin>
        </a-card>
        <div class="flex flex-a-c h-20 mb-14 mt-14">
          <div class="h-full bg-theme round-2 w-4 mr-10"></div>
          <span class="font-size-30 text333">用户明细</span>
        </div>
        <a-card class="mt-m" :bordered="false">
          <a-table
            stripe
            :sticky-header="-1"
            row-key="date"
            v-model:columns="columns"
            :loading="staticLoading"
            :data="dataList"
            :scroll="{ x: '100%', y: '100%' }"
            :pagination="false"
          >
          </a-table>
        </a-card>
      </a-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { userDaysInfo, userMergeInfo } from '@/apis'
import { reAssign } from '@/utils/common'
import { totalDataO } from './data.js'
import dayjs from 'dayjs'
import Chart from './Chart.vue'
const props = defineProps(['allChannel'])
const staticLoading = ref(false)
const topLoading = ref(false)
const ChartRef = ref()
const checkKey = ref(['newUserTotal'])
const tabIndex = ref()
const dateTime = ref()
const dateDefault = ref()
const dataShow = ref(false)
const staticParams = reactive({
  channelUserIds: [],
  channelIds: []
})
const dataList = ref([])
const dataFormat = ref({
  date: [],
  newUserTotal: [],
  newUserOrderTotal: [],
  firstOrderTotal: [],
  firstValidOrderTotal: [],
  newUserBuyValidOrder: []
})

const totalDatas = reactive({
  newUserTotal: 0,
  newUserOrderTotal: 0,
  firstOrderTotal: 0,
  firstValidOrderTotal: 0,
  newUserBuyValidOrder: 0
})

const columns = [
  {
    title: '日期',
    width: 120,
    align: 'center',
    dataIndex: 'date'
  },
  {
    title: '新注册用户',
    width: 110,
    align: 'center',
    dataIndex: 'newUserTotal'
  },
  {
    title: '新注册用户（已下单）',
    width: 120,
    align: 'center',
    dataIndex: 'newUserOrderTotal'
  },
  {
    title: '新注册用户（有效下单）',
    width: 120,
    align: 'center',
    dataIndex: 'firstOrderTotal'
  },
  {
    title: '初次下单用户',
    width: 120,
    align: 'center',
    dataIndex: 'firstValidOrderTotal'
  },
  {
    title: '初次下单用户（仅有效单）',
    width: 120,
    align: 'center',
    dataIndex: 'newUserBuyValidOrder'
  }
]

if (props?.allChannel?.length) {
  staticParams.channelIds = props.allChannel.map((item) => {
    return item.channelId
  })
  staticParams.channelUserIds = props.allChannel.map((item) => {
    return item.channelUserId
  })
}

const getTop = async () => {
  try {
    topLoading.value = true
    const startAt = dateTime.value[0].format('YYYY-MM-DD HH:mm:ss')
    const endAt = dateTime.value[1].format('YYYY-MM-DD HH:mm:ss')
    const res = await userMergeInfo({
      startAt,
      endAt,
      channelIds: staticParams.channelIds,
      channelUserIds: staticParams.channelUserIds
    })
    reAssign(totalDatas, res.data)
  } finally {
    topLoading.value = false
  }
}
// 获取数据
const onGetStatic = async () => {
  try {
    staticLoading.value = true
    const startAt = dateTime.value[0].format('YYYY-MM-DD HH:mm:ss')
    const endAt = dateTime.value[1].format('YYYY-MM-DD HH:mm:ss')
    const res = await userDaysInfo({
      startAt,
      endAt,
      channelIds: staticParams.channelIds,
      channelUserIds: staticParams.channelUserIds
    })
    const objSource = {}
    const daysListReverse = JSON.parse(JSON.stringify(res.data))
    dataList.value = res.data.reverse()
    daysListReverse.forEach((item) => {
      Object.keys(item).forEach((key) => {
        if (!objSource[key]) objSource[key] = []
        if (
          [
            'newUserTotal',
            'newUserOrderTotal',
            'firstOrderTotal',
            'firstValidOrderTotal',
            'newUserBuyValidOrder'
          ].includes(key)
        ) {
          item[key] = Number(item[key])
        }
        objSource[key].push(item[key])
      })
    })
    dataFormat.value = objSource
  } finally {
    staticLoading.value = false
  }
}

const changeData = (index) => {
  tabIndex.value = index
  switch (index) {
    case 1:
      dateTime.value = [dayjs().startOf('day'), dayjs().endOf('day')]
      break
    case 2:
      dateTime.value = [dayjs().subtract(7, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')]
      break
    case 3:
      dateTime.value = [dayjs().subtract(15, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')]
      break
    case 4:
      dateTime.value = [dayjs().subtract(30, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')]
      break
    case 5:
      dateTime.value = [dayjs().startOf('month'), dayjs().endOf('day')]
      break
    case 6:
      dateTime.value = [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')]
      break
  }
  onGetStatic()
  getTop()
}

const dataChange = (flag) => {
  if (flag) tabIndex.value = null
  onGetStatic()
  getTop()
}

const channelIdsChange = (e) => {
  const channelUserIds = props.allChannel.filter((item) => e.includes(item.channelId)).map((item) => item.channelUserId)
  staticParams.channelIds = e
  staticParams.channelUserIds = channelUserIds
  onGetStatic()
  getTop()
}

// 打开日期选择框
const openCalendar = () => {
  if (dateTime.value) {
    dateDefault.value = [dateTime.value[0].toDate(), dateTime.value[1].toDate()]
  }
  dataShow.value = true
}
// 日期选择回调
const onConfirmDate = (e) => {
  dateTime.value = [dayjs(e[0]).startOf('day'), dayjs(e[1]).endOf('day')]
  dataShow.value = false
  dataChange(true)
}

onMounted(() => {
  setTimeout(() => {
    changeData(2)
  }, 1000)
})
</script>

<style lang="scss" scoped>
.text23 {
  color: #232323;
}
.custom-checkbox-card {
  padding: 9px 10px 10px 10px;
  border: 1px solid #62b793;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 7px;
}

.custom-checkbox-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  border: 1px solid #62b793;
  box-sizing: border-box;
  margin-top: 3px;
}

.custom-checkbox-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}

.custom-checkbox-card-title {
  color: var(--color-text-1);
  font-size: 10px;
  font-weight: bold;
}

.custom-checkbox-card:hover,
.custom-checkbox-card-checked,
.custom-checkbox-card:hover .custom-checkbox-card-mask,
.custom-checkbox-card-checked .custom-checkbox-card-mask {
  border-color: #62b793;
}

.custom-checkbox-card-checked {
  background-color: #f3fffa;
}

.custom-checkbox-card:hover .custom-checkbox-card-title,
.custom-checkbox-card-checked .custom-checkbox-card-title {
  color: #62b793;
}

.custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
  background-color: #62b793;
}

.arco-scrollbar {
  height: 100%;
}

.w-1-4 {
  width: 20%;
}

.select-box {
  :deep(.arco-select-dropdown-list-wrapper) {
    max-height: 300px !important;
  }
}

.text463AC9 {
  color: #463ac9;
}

.text22A164 {
  color: #22a164;
}
.bgF7F7F7 {
  background-color: #f7f7f7;
}

.dashboard-item {
  :deep(.arco-card-body) {
    padding: 20px 12px;
  }
}

.st-item {
  width: calc((100% - 12px) / 3);
  margin-bottom: 14px;
}

:deep(.arco-checkbox) {
  margin-right: 0;
}

:deep(.arco-statistic-value) {
  font-size: 16px;
}

:deep(.arco-table-col-fixed-right .arco-table-cell) {
  padding: 5px 0 !important;
}
</style>
